import numpy as np
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
import matplotlib.pyplot as plt

# 1.	对以下内容进行处理操作，完成线性回归操作（70分）
# (1)	数据处理
# ①	加载boston数据集
# ②	切分x,y
x, y = load_boston(return_X_y=True)

# ③	将数据集切分为训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.7)

# (2)	模型管道处理
# ①	创建管道
# ②	管道内加载pca降维降到4维
# ③	创建线性回归并加载到管道
# ④	加处理好的管道进行训练
pipe = Pipeline([
    ['pca', PCA(n_components=4)],
    ['lin_reg', LinearRegression()]
])
pipe.fit(x_train, y_train)
print(f'Training score = {pipe.score(x_train, y_train)}')

# (3)	模型评测
# ①	打印测试集评测结果
print(f'Testing score = {pipe.score(x_test, y_test)}')

# ②	绘制测试集实际值和预测值折线图
plt.scatter(y, y, s=1, c='b', zorder=100, label='target')
h = pipe.predict(x)
plt.scatter(y, h, s=1, c='r', zorder=0, label='hypothesis')
plt.legend()

plt.show()

